package com.cndw.kungfu.model.activity.domain;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicInteger;

import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.StringProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.goods.domain.SubPops;
import com.cndw.kungfu.model.pvp.api.ApiCore;
import com.cndw.kungfu.model.pvp.api.CommApiClient;
import com.cndw.kungfu.model.sys.ChatMain;

/**
 * 烽火九州 数据处理类
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2012-11-8 下午6:02:56
 */
public class BalefileStaticeData {
	/**
	 * 在单服存放数据 id和数字号
	 */
	private static final ConcurrentHashMap<Long, Integer> fireIdsMap = new ConcurrentHashMap<Long, Integer>();
	/**
	 * 在跨服存放数据 id和服务器号
	 */
	private static final ConcurrentHashMap<Long, Integer> fire99IdsMap = new ConcurrentHashMap<Long, Integer>();
	private static final ConcurrentHashMap<Long, String> fire99NamesMap = new ConcurrentHashMap<Long, String>();
	/**
	 * 在跨服记录状态
	 */
	private static boolean open = false;
	/**
	 * 在跨服统计编号
	 */
	private static AtomicInteger signUser = new AtomicInteger(0);

	private static AtomicInteger signSys = new AtomicInteger(0);
	/**
	 * 活动时间区间
	 */
	public static final int[] timeArea = { 20 * 3600 + 1800, 21 * 3600 };

	public static int timeFix = 300;

	public static int signMax = 90000;

	public static final int rebotStep = 10;

	public static int lastAward = 0;

	private static ScheduledFuture<?> task;

	private static final int luckNum = 99;

	public static int crossAdd(int sid, long uid, String name) {
		if (!open) {
			return -1;
		}
		int currentId = signUser.incrementAndGet();// 用户数据+1
		signSys.incrementAndGet();// 系统数据+1
		int currentSign = currentId % 100;
		if (currentSign == luckNum) {
			fire99IdsMap.put(uid, sid);
			fire99NamesMap.put(uid, name);
		} else if (currentSign < luckNum - 5) {// 虚拟修改数字
			signUser.compareAndSet(currentId, currentId + (NumberProcesser.isWinning(50) ? 1 : 2));
		}
		return currentSign;
	}

	public static void currentAdd(long uid, int ret) {
		if (ret == luckNum || !fireIdsMap.containsKey(uid) || fireIdsMap.get(uid) != luckNum) {
			fireIdsMap.put(uid, ret);
		}
	}

	public static void runBoss() {
		if (!ApiCore.isCrossServer()) {
			return;
		}
		int currentTime = TimeProcesser.getUnixTime();
		int morningTime = TimeProcesser.getMorningTime();
		int startTime = morningTime + timeArea[0];
		int endTime = morningTime + timeArea[1];
		if (endTime <= currentTime) {
			startTime += 86400;
			endTime += 86400;
		}
		int initialDelay = startTime - currentTime;
		Runnable command = new Runnable() {

			@Override
			public void run() {
				runStart();
			}
		};
		Context.getTimerServer().scheduleAtFixedRate(command, initialDelay, 86400);

	}

	private static synchronized void runStart() {
		open = true;
		clearData(true);

		int delay = TimeProcesser.getMorningTime() + timeArea[1] - TimeProcesser.getUnixTime();
		timeFix = NumberProcesser.mtRand(0, NumberProcesser.between(delay - 10, 1, 300));
		LogUtil.getMain().debug("balefile start ..." + timeFix);

		Context.getTimerServer().scheduleSeconds(new Runnable() {

			@Override
			public void run() {
				runStop(false);

			}
		}, delay);

		task = Context.getTimerServer().scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				runReboot();

			}
		}, rebotStep);
	}

	private static synchronized void runStop(boolean ok) {
		if (!open) {
			return;
		}

		LogUtil.getMain().debug("balefile stop ..." + ok);
		open = false;
		StringBuilder sb = new StringBuilder();
		StringBuilder ticp = new StringBuilder();
		try {
			ArrayList<Long> ids = new ArrayList<Long>(fire99IdsMap.keySet());
			Collections.shuffle(ids);
			int num = 0;
			for (Long okId : ids) {
				num++;
				sb.append(okId);
				ticp.append("S" + fire99IdsMap.get(okId) + fire99NamesMap.get(okId));
				if (num >= 9) {// 退出
					break;
				}
				sb.append(StringProcesser.SPLIT);
				ticp.append(StringProcesser.SPLIT);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		clearData(false);

		CommApiClient.balefireAward(sb.toString(), ticp.toString());// 发送奖励了
	}

	/**
	 * 潜规则机器人
	 */
	private static synchronized void runReboot() {
		check();
		if (!open) {
			return;
		}

		int currentTime = TimeProcesser.getUnixTime();
		int morningTime = TimeProcesser.getMorningTime();

		int leaveTime = morningTime + timeArea[1] - currentTime - timeFix;
		int leave = signMax - signSys.get();

		int speedleave = leave / leaveTime;

		int add = (speedleave) * rebotStep;
		//int old = signSys.get();
		signSys.addAndGet(add);
		//LogUtil.getMain().debug("speed " + speedleave + " leave " + leaveTime + " add " + add + " old " + old + "->" + signSys.get());
	}

	private static void check() {
		if (!open) {
			return;
		}
		if (signSys.get() >= signMax) {
			runStop(true);
		}
	}

	public static int getState() {
		return NumberProcesser.floor(signSys.get(), signMax / 9);
	}

	private static synchronized void clearData(boolean open) {
		// fireIdsMap.clear();
		fire99IdsMap.clear();
		fire99NamesMap.clear();
		signSys.set(0);
		signUser.set(0);
		if (task != null) {
			try {
				task.cancel(false);
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 接受信息 处理奖励
	 * 
	 * @param idstr
	 * @param ticp
	 * @return
	 */
	public static void prossAwar(final String idstr, final String ticp) {
		Context.getTimerServer().scheduleSeconds(new Runnable() {
			@Override
			public void run() {
				prossAwarExec(idstr, ticp);
			}
		}, NumberProcesser.mtRand(10));

	}

	public static void prossAwarExec(String idstr, String ticp) {
		if (lastAward == TimeProcesser.getMorningTime()) {
			return;
		}
		lastAward = TimeProcesser.getMorningTime();

		LogUtil.getMain().debug("ids map size " + fireIdsMap.size());

		ChatMain.systemMessage(LanguageLib.get("meet.fire.end"));
		ChatMain.systemMessage(LanguageLib.get("meet.fire.board", ticp));
		Set<Long> fire99BigIds = new HashSet<Long>();
		try {
			fire99BigIds = StringProcesser.toLongSet(idstr, StringProcesser.SPLIT);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (fire99BigIds == null) {
			fire99BigIds = new HashSet<Long>();
		}
		Set<Long> onlineIds = Context.getTcpServer().allOnLineIds();
		int type = 0;
		int[] goodsArr = { 103619, 103620, 103621, 103622 };
		String title = LanguageLib.get("meet.fire.title");
		String content;

		int num = 0;

		for (Long uid : onlineIds) {
			num++;
			type = 0;
			if (fire99BigIds.contains(uid)) {
				type = 3;
			} else if (fireIdsMap.containsKey(uid)) {
				if (fireIdsMap.get(uid) == luckNum) {
					type = 2;
				} else {
					type = 1;
				}
			}
			Player player = Context.getPlayerServer().getByPlayerId(uid);
			if (player.getLevel() < ConstantsLevel.lv30balefire) {
				continue;
			}
			if (player != null) {
				int goodsId = goodsArr[type];
				GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
				if (goodsMode == null) {
					continue;
				}

				content = LanguageLib.get("meet.fire.content", goodsMode.getName());
				List<SubPops> attachment = new ArrayList<SubPops>();
				attachment.add(new SubPops(goodsId, 1, 1));

				Context.getMessageServer().sendSysMail(player.getPlayerId(), player.getPlayerName(), title, content, attachment);
			}

		}
		LogUtil.getMain().debug("fire award " + num);

		fireIdsMap.clear();// 清理本服的数据
	}

}
